﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Models;
using System.Configuration;
using Code.Commen;
using log4net;
using System.Data.Common;

namespace Code.DAL
{
    public class DBHelper
    {
        /// <summary>
        /// 数据源
        /// </summary>
        internal static DBContext DBContext
        {
            get
            {
                var db = new DBContext(GetConnectionString());
                return db;
                //return new DBContext();
            }
        }

        /// <summary>
        /// 日志记录对象
        /// </summary>
        private static ILog Log = Code.Commen.Log.GetLog("Code.DAL.DBHelper");

        private static string GetConnectionString()
        {
            string connectionString = "";

            string constrtype = ConfigurationManager.AppSettings["ConType"];

            //获取config  ConnectionStrings的配置节
            ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["DBConnectionString"];
            string constr = setting.ConnectionString;
            if (string.IsNullOrEmpty(constrtype) || !constrtype.Equals("Normal", StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    DES des = new DES();
                    var salt = Salt.Generic.GetDesSalt();
                    //解密
                    connectionString = des.DecryptString(constr, salt.Key, salt.Value);
                }
                catch (Exception e)
                {
                    if (Log.IsDebugEnabled)
                        Log.Debug(e.Message, e);
                    if (Log.IsWarnEnabled)
                        Log.Warn("连接字符串格式不正确！");
                }
            }
            else
            {
                connectionString = constr;
            }
            return connectionString;
        }

        /// <summary>
        /// 获取连接对像
        /// </summary>
        /// <returns></returns>
        public static DbConnection Connection
        {
            get
            {
                var consit = ConfigurationManager.ConnectionStrings["DBConnectionString"];

                if (consit == null)
                {
                    throw new System.InvalidOperationException("不存在DBConnectionString");
                }

                var factory = DbProviderFactories.GetFactory(consit.ProviderName);
                var con = factory.CreateConnection();
                con.ConnectionString = GetConnectionString();
                return con;
            }
        }
    }
}
